import 'dart:developer';

import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/course/models/course_response.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class CategoryPageLogic extends ChangeNotifier {
  List<CourseCategory>? categories;

  bool isLoading = false;
  bool isError = false;

  bool get isCategoryEmpty => categories == null || categories!.isEmpty;

  // 主分类索引
  int _majorCategoryIndex = 0;
  int get majorCategoryIndex => _majorCategoryIndex;
  set majorCategoryIndex(int index) {
    _majorCategoryIndex = index;
    notifyListeners();
  }

  // 获取当前选中的一级分类id
  int get majorCategoryId {
    if (categories == null) {
      return 0;
    } else {
      final majorCategory = categories![_majorCategoryIndex];
      return majorCategory.id;
    }
  }

  // 获取当前选中的二级分类
  List<CourseSubcategory>? get minorCategories {
    if (categories == null) {
      return null;
    } else {
      final majorCategory = categories![_majorCategoryIndex];
      return majorCategory.subCategories;
    }
  }

  List<String>? topCourseKeys;

  // 获取当前选中的课程
  CategoryPageLogic();

  void init() {
    Future.delayed(Duration.zero, () {
      loadCourseCategories();
      loadTopCourseKeys();
    });
  }

  // 访问后端接口
  Future<void> loadCourseCategories() async {
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      isLoading = true;
      isError = false;
      notifyListeners();

      final response = await DataFetcher.shared.courseApi.getAllCategories();
      isLoading = false;
      EasyLoading.dismiss();

      if (response.code == 0 && response.categories != null) {
        categories = response.categories;
      } else {
        isError = true;
        categories = null;
        EasyLoading.showError(response.message ?? AppStrings.courseError);
      }
      notifyListeners();
    } catch (e) {
      isLoading = false;
      isError = true;
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      notifyListeners();
    }
  }

  Future<void> loadTopCourseKeys() async {
    try {
      final response = await DataFetcher.shared.courseApi.getTopCourseKeys();
      if (response.code == 0 && response.keys != null) {
        final keys = response.keys!;
        var tmp = '';
        final groupedKeys = <String>[];
        for (var i = 0; i < keys.length; i++) {
          tmp += '${keys[i]} · ';
          if (i != 0 && i % 3 == 2) {
            tmp = tmp.substring(0, tmp.length - 3);
            groupedKeys.add(tmp);
            tmp = '';
          }
        }
        if (tmp.isNotEmpty) {
          tmp = tmp.substring(0, tmp.length - 3);
          groupedKeys.add(tmp);
        }

        topCourseKeys = groupedKeys;
        notifyListeners();
      } else if (response.code != 0) {
        topCourseKeys = null;
      }
    } catch (e) {
      topCourseKeys = null;
    }
  }
}
